<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Story_Model extends CI_Model {
	
	public function get_story($username) {
		$query = "SELECT * FROM smb_student_stories WHERE username = ?";
		$result = $this->db->query($query, array($username));
		if ($result->num_rows() == 1) {
			return $result->row();
		} else {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return NULL;
		}
	}
	
	public function update_story($username, $story) {
		$exists = $this->get_story($username);
		if ($exists == NULL) {
			$query = "INSERT INTO smb_student_stories (story, username, date) VALUES (?, ?, CURRENT_TIMESTAMP)";
		} else {
			$query = "UPDATE smb_student_stories SET story = ?, date = CURRENT_TIMESTAMP WHERE username = ?";
		}
		
		$this->db->trans_start();
		$this->db->query($query, array($story, $username));
		$this->db->trans_complete();
		
		if ($this->db->trans_status() === FALSE) {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return FALSE;
		} else {
			return TRUE;
		}
	}
}